#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 4e4 + 10, M = N * 2;
int h[N], e[M], ne[M], idx;
int depth[N], fa[N][16];
int q[N];
int n, m;
int x, y;
void add(int a, int b)
{
	e[idx] = b;
	ne[idx] = h[a];
	h[a] = idx++;
}

void bfs(int root)
{
	memset(depth, 0x3f, sizeof(depth));
	depth[0] = 0, depth[root] = 1;
	int hh = 0, tt = 0;
	q[0] = root;
	while (hh <= tt) {
		int t = q[hh++];
		for (int i = h[t]; ~i; i = ne[i]) {
			int j = e[i];
			if (depth[j] > depth[t] + 1) {
				depth[j] = depth[t] + 1;
				q[++tt] = j;
				fa[j][0] = t;
				for (int k = 1; k <= 15; k++) {
					fa[j][k] = fa[fa[j][k - 1]][k - 1];
				}
			}
		}
	}
}

int lca(int a, int b)
{
	if (depth[a] < depth[b])  swap(a, b);
	for (int k = 15; k >= 0; k--) {
		if (depth[fa[a][k]] >= depth[b]) {
			a = fa[a][k];
		}
	}
	if (a == b) {
		return a;
	}
	for (int k = 15; k >= 0; k--) {
		if (fa[a][k] != fa[b][k]) {
			a = fa[a][k];
			b = fa[b][k];
		}
	}
	return fa[a][0];
}
int main()
{
	cin >> n;
	int root = 0;
	memset(h, -1, sizeof(h));
	while (n--) {
		cin >> x >> y;
		if (y == -1)root = x;
		else
			add(x, y), add(y, x);
	}
	bfs(root);
	cin >> m;
	while (m--) {
		cin >> x >> y;
		int p = lca(x, y);
		if (p == x)
			cout << "1" << endl;
		else if (p == y)
			cout << "2" << endl;
		else
			cout << "0" << endl;
	}
	return 0;
}